﻿using System;
using System.Collections.Generic;
using System.Web;

namespace WeMakeSP.WebComponents.RSSAdvancedReaderWebPart
{
    /// <summary>
    /// Represents an RSS advanced reader configuration loader.
    /// </summary>
    public static class RSSAdvancedReaderConfigurationLoader
    {
        #region Constants

        /// <summary>
        /// The feeds separator.
        /// </summary>
        private const char Separator = ';';

        #endregion

        #region Static Methods

        /// <summary>
        /// Loads the specified feeds.
        /// </summary>
        /// <param name="view">The RSS advanced reader view.</param>
        /// <returns>A collection of feed configurations.</returns>
        public static RSSAdvancedReaderFeedConfigurationCollection Load(IRSSAdvancedReaderView view)
        {
            // Guard.

            if (view == null)
            {
                throw new ArgumentNullException("view");
            }

            if (view.Feeds == null)
            {
                throw new ArgumentNullException("view.Feeds");
            }

            // Get the properties.

            string feeds = view.Feeds;
            int limit = view.Limit;
            RSSAdvancedReaderItemView itemView = view.ItemView;
            bool showFeedImage = view.ShowFeedImage;
            bool showFeedItemPublicationDate = view.ShowPublicationDate;

            // Split the string.

            string[] parsedFeeds =
                feeds.Split(new char[] { Separator });

            RSSAdvancedReaderFeedConfigurationCollection feedConfigurations =
                new RSSAdvancedReaderFeedConfigurationCollection();

            // Iterate throught the feeds.

            foreach (string parsedFeed in parsedFeeds)
            {
                // Check if the Uri is valid.

                bool isValidUri =
                    Uri.IsWellFormedUriString(parsedFeed, UriKind.RelativeOrAbsolute) &&
                    !string.IsNullOrEmpty(parsedFeed);

                if (isValidUri)
                {
                    // Add the feed to the configuration list.

                    feedConfigurations.Add(
                        new RSSAdvancedReaderFeedConfiguration()
                        {
                            Limit = limit,
                            Link = parsedFeed,
                            ShowImage = showFeedImage,
                            ShowPublicationDate = showFeedItemPublicationDate,
                            View = itemView
                        });
                }
            }

            // Returns.

            return feedConfigurations;
        }

        #endregion
    }
}
